package com.lemurian.bankdata.bean;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.lemurian.bankdata.bean.base.BaseDaoHibernate;
import com.lemurian.bankdata.lite.logger.BankDataLogger;
import com.lemurian.entity.Menu;

@Repository
public class MenuDAO extends BaseDaoHibernate<Menu>{
	
	private BankDataLogger log = BankDataLogger.getLogger(MenuDAO.class.getName());

	@Override
	public Menu load(int id){
		Menu entity = null;
		try {
			Criteria criteria = getSession().createCriteria(Menu.class);
			
			criteria.setCacheable(Boolean.TRUE);
			
			criteria.createCriteria("parent", "parent", Criteria.LEFT_JOIN)
				.setCacheRegion(Menu.class.getName());
			
			criteria.add(Restrictions.eq("id", id));
			
			entity = (Menu) criteria.uniqueResult();
			
		} catch(Exception exception){
			getSession().getTransaction().rollback();
		}
		return entity;
	}
	
	@SuppressWarnings("unchecked")
	public List<Menu> parents(int parentId) {
		List<Menu> parents = null;
		
		try {
			
			Criteria criteria = getSession().createCriteria(Menu.class);
			
			criteria.setCacheable(Boolean.TRUE);
			
			criteria.createCriteria("parent", "parent", Criteria.LEFT_JOIN)
					.setCacheRegion(Menu.class.getName());
			
			criteria.add(Restrictions.eq("parent.id", parentId));
			
			parents = criteria.list();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return parents;
	}

	@SuppressWarnings("unchecked")
	public List<Menu> parents() {
		List<Menu> parents = null;
		
		try {
			
			Criteria criteria = getSession().createCriteria(Menu.class);
			
			criteria.setCacheable(Boolean.TRUE);
			
			criteria.add(Restrictions.eq("showParent", Boolean.TRUE));
			
			parents = criteria.list();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return parents;
	}
	
	public void deleteAllParent(Menu entity) throws Exception {
        try {
            int delete = getSession().createQuery("delete "+Menu.class.getName()+" o where o.parent.id='"+entity.getId()+"' or o.id='"+entity.getId()+"'").executeUpdate();

            log.info("delete menu and all parent : "+delete);
        } catch(Exception e) {
            log.info("error delete menu and all parent : "+e.getMessage());
            e.printStackTrace();
        }
    }
}
